#include <iostream>
#include <string>
#include <fcntl.h>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
using namespace std;

#define PATH "./fifo"

int main()
{
  umask(0);
  int status = mkfifo(PATH, 0666);
  if (status == 0)
  {
    cout << "mkfifo success" << endl;
  }
  else
  {
    cerr << "mkfifo failed, errno: " << errno << ", errstring: " << strerror(errno) << endl;
  }
  pid_t ret = fork();
  if (ret == 0)
  {
    int wfd = open(PATH, O_WRONLY);
    if (wfd < 0)
    {
      cerr << "open failed, errno: " << errno << ", errstring: " << strerror(errno) << endl;
      return 1;
    }
    string inbuffer;
    cout << "Please Enter Your Message# " << endl;
    std::getline(cin, inbuffer);
    ssize_t n = write(wfd, inbuffer.c_str(), inbuffer.size());
    if (n < 0)
    {
      cerr << "write failed, errno: " << errno << ", errstring: " << strerror(errno) << endl;
    }
    close(wfd); // 通信完毕，关闭命名管道文件
  }
  // wait(nullptr);

  int rfd = open(PATH, O_RDONLY);
  if (rfd < 0)
  {
    cerr << "open failed, errno: " << errno << ", errstring: " << strerror(errno) << endl;
    return 1;
  }
  // 如果我们的写端没打开，先读打开，open的时候就会阻塞，直到把写端打开，读open才会返回
  cout << "open success" << endl;

  char buffer[1024];

  ssize_t n = read(rfd, buffer, sizeof(buffer) - 1);
  if (n > 0)
  {
    buffer[n] = 0; // 加上'\0'方便输出
    cout << "GET MESSAGE : " << buffer << endl;
  }
  close(rfd);
  return 0;
}